package com.oracle.application.config;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.oracle.application.entity.Orders;
import com.oracle.application.entity.Paylog;
import com.oracle.application.entity.vo.PayAsyncVo;
import com.oracle.application.entity.vo.PayVo;
import com.oracle.application.service.IOrdersService;
import com.oracle.application.service.IPaylogService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;

@ConfigurationProperties(prefix = "payconfig")
@Component
@Data
@NoArgsConstructor
@AllArgsConstructor
@Slf4j
public class PayConfig {
    @Autowired
    private IPaylogService iPaylogService;
    @Autowired
private IOrdersService iOrdersService;


    private String app_id;
    private String payGateway;
    private String notify_url;
    private String return_url;
    private String publicKey;
    private String privateKey;


    public  String doPay(PayVo payVo, Integer orderId){
        AlipayClient client=new DefaultAlipayClient(payGateway,app_id,privateKey,"json","utf-8",publicKey,"RSA2");
        AlipayTradePagePayRequest request=new AlipayTradePagePayRequest();
        request.setReturnUrl(return_url);
        request.setNotifyUrl(notify_url);
        Paylog paylog=new Paylog();
        paylog.setPayprice(new BigDecimal(payVo.getTotal_amount()));
        paylog.setOrdersn(payVo.getOut_trade_no());
        paylog.setCreatedate(LocalDateTime.now());
        paylog.setModifydate(LocalDateTime.now());
        paylog.setOrders(orderId);
        paylog.setContent("订单编号为:"+payVo.getOut_trade_no()+LocalDateTime.now()+"正在向支付宝发起支付,支付金额为"+payVo.getTotal_amount());
        paylog.setStatus(2);
        paylog.setMember(1);
        this.iPaylogService.save(paylog);
        payVo.setPassback_params(paylog.getId()+"");
        request.setBizContent(JSONObject.toJSONString(payVo));
        String resultPage=null;
        try {
            resultPage=client.pageExecute(request).getBody();
            return resultPage;
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return resultPage;
    }

    public  boolean returnVerifySignature(PayAsyncVo payAsyncVo){
       String ordersn1=payAsyncVo.getOut_trade_no();
        Orders orders=new Orders();
        orders.setOrdersn(ordersn1);
        QueryWrapper<Orders> wrapper=new QueryWrapper<Orders>(orders);
         orders=this.iOrdersService.getOne(wrapper);
        if (orders.getOrderstatus()==1){
            return true;
        }

        return false;
    }

    public  boolean verifySignature(PayAsyncVo payAsyncVo){
        Map<String,String> params=JSONObject.parseObject(JSONObject.toJSONString(payAsyncVo),Map.class);
        System.out.println("异步验签----------------------");
        try {
            boolean b=AlipaySignature.rsaCheckV1(params,publicKey,"utf-8","RSA2");
            System.out.println(b+"===================b===");
            if (b){
               log.info("异步回调验签通过");
               Integer  payLogId=Integer.parseInt(payAsyncVo.getPassback_params());
               Paylog paylog=this.iPaylogService.getById(payLogId);

                System.out.println(!payAsyncVo.getOut_trade_no().equals(paylog.getOrdersn())+"]]]]]]]]]]]]]]]]]]]");
               if (!payAsyncVo.getOut_trade_no().equals(paylog.getOrdersn())){
                   return  false;
               }
                System.out.println(!payAsyncVo.getInvoice_amount().equals(paylog.getPayprice().toString())+"---------------");
               if (!payAsyncVo.getInvoice_amount().equals(paylog.getPayprice().toString())){
                   return false;
               }
                System.out.println(payAsyncVo.getTrade_status()+"=============");
               if ("TRADE_SUCCESS".equals(payAsyncVo.getTrade_status())){
                   String content=paylog.getContent();
                   StringBuffer payLogBuffer=new StringBuffer(content);
                   payLogBuffer.append("订单编号为:"+payAsyncVo.getOut_trade_no()+LocalDateTime.now()+"支付成功");
                   paylog.setContent(payLogBuffer.toString());
                   paylog.setStatus(1);
                   this.iPaylogService.updateById(paylog);
                   if (this.iOrdersService.updateOrderStatus(payAsyncVo.getOut_trade_no())>0){
                       return true;
                   }
                   return  false;
               }
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
return  false;
    }
}


